$(document).ready(function () {

    ///Set Timepickers
    //$('#startDate').datetimepicker({
    //    timeFormat: 'HH:mm:ss',
    //    dateFormat: 'dd/mm/yy'
    //});
    //$('#endDate').datetimepicker({
    //    timeFormat: 'HH:mm:ss',
    //    dateFormat: 'dd/mm/yy'
    //});
    var startDateTextBox = $('#startDate');
    var endDateTextBox = $('#endDate');

    startDateTextBox.datetimepicker({
        timeFormat: 'HH:mm:ss',
        dateFormat: 'dd/mm/yy',
        onClose: function (dateText, inst) {
            if (endDateTextBox.val() != '') {
                var testStartDate = startDateTextBox.datetimepicker('getDate');
                var testEndDate = endDateTextBox.datetimepicker('getDate');
                if (testStartDate > testEndDate)
                    endDateTextBox.datetimepicker('setDate', testStartDate);
            }
            else {
                endDateTextBox.val(dateText);
            }
        },
        onSelect: function (selectedDateTime) {
            endDateTextBox.datetimepicker('option', 'minDate', startDateTextBox.datetimepicker('getDate'));
        }
    });
    endDateTextBox.datetimepicker({
        timeFormat: 'HH:mm:ss',
        dateFormat: 'dd/mm/yy',
        onClose: function (dateText, inst) {
            if (startDateTextBox.val() != '') {
                var testStartDate = startDateTextBox.datetimepicker('getDate');
                var testEndDate = endDateTextBox.datetimepicker('getDate');
                if (testStartDate > testEndDate)
                    startDateTextBox.datetimepicker('setDate', testEndDate);
            }
            else {
                startDateTextBox.val(dateText);
            }
        },
        onSelect: function (selectedDateTime) {
            startDateTextBox.datetimepicker('option', 'maxDate', endDateTextBox.datetimepicker('getDate'));
        }
    });


    var startDateTextBoxCompare = $('#compareStart');
    var endDateTextBoxCompare = $('#compareEnd');

    startDateTextBoxCompare.datetimepicker({
        timeFormat: 'HH:mm:ss',
        dateFormat: 'dd/mm/yy',
        onClose: function (dateText, inst) {
            if (endDateTextBoxCompare.val() != '') {
                var testStartDate = startDateTextBoxCompare.datetimepicker('getDate');
                var testEndDate = endDateTextBoxCompare.datetimepicker('getDate');
                if (testStartDate > testEndDate)
                    endDateTextBoxCompare.datetimepicker('setDate', testStartDate);
            }
            else {
                endDateTextBoxCompare.val(dateText);
            }
        },
        onSelect: function (selectedDateTime) {
            endDateTextBoxCompare.datetimepicker('option', 'minDate', startDateTextBoxCompare.datetimepicker('getDate'));
        }
    });

    endDateTextBoxCompare.datetimepicker({
        timeFormat: 'HH:mm:ss',
        dateFormat: 'dd/mm/yy',
        onClose: function (dateText, inst) {
            if (startDateTextBoxCompare.val() != '') {
                var testStartDate = startDateTextBoxCompare.datetimepicker('getDate');
                var testEndDate = endDateTextBoxCompare.datetimepicker('getDate');
                if (testStartDate > testEndDate)
                    startDateTextBoxCompare.datetimepicker('setDate', testEndDate);
            }
            else {
                startDateTextBoxCompare.val(dateText);
            }
        },
        onSelect: function (selectedDateTime) {
            startDateTextBoxCompare.datetimepicker('option', 'maxDate', endDateTextBoxCompare.datetimepicker('getDate'));
        }
    });

    /// Get USER ID
    function getUserID() {
        var userID = $.ajax({
            type: 'GET',
            url: "scripts/GetSessions.aspx",
            data: { "UserId": "true" },
            dataType: 'html',
            global: false,
            async: false,
            success: function (data) {
                return data;
            }
        }).responseText;

        return userID;
    }

    function loadDeviceList() {
        var devices = $.ajax({
            type: 'GET',
            url: "http://uclwebservicetest.cloudapp.net/Services/users.svc/devices/list?userid=" + getUserID() + "&privacy=all",
            contentType: "application/json; charset=utf-8",
            global: false,
            async: false,
            success: function (data) {
                return data;
            }
        }).responseText;

        var obj = jQuery.parseJSON(devices);

        if (obj.ErrorDetail == "No device exists for this user") {
            return "401"; // No Device Found
        } else {
            return devices;
        }
    }

    function loadSensorList(deviceID) {
        var sensors = $.ajax({
            type: 'GET',
            url: "http://uclwebservicetest.cloudapp.net/Services/users.svc/sensors?deviceid=" + deviceID,
            contentType: "application/json; charset=utf-8",
            global: false,
            async: false,
            success: function (data) {
                return data;
            }
        }).responseText;

        var obj = jQuery.parseJSON(sensors);

        if (obj.ErrorDetail == "Retrieval Failed.Nullable object must have a value."
            || obj.ErrorDetail == "There no sensors associated with this Device") {
            $('#info').fadeIn(1000);
            $('#info').html('There are no sensors associated with this device. Either register one or choose another device from the available ones.');
            $('#row-sensors').hide();
            // return false;
        } else {
            $('#info').hide();
            return sensors;
        }
    }

    var devicelist = loadDeviceList();
    var devices = $.parseJSON(devicelist);
    var deviceListDropDown;

    deviceListDropDown = "<option value='-1'>-Any-</option>";
    $.each(devices, function (i, devicelist) {
        deviceListDropDown += "<option value='" + devicelist.response.Id + "'>" + devicelist.response.Name + "</option>";
    });

    $('#device-list').html(deviceListDropDown);

    ///Append the same to Compare Section
    $('#compareDeviceNameScenario1').html(deviceListDropDown);
    $('#compareDeviceNameScenario2').html(deviceListDropDown);

    /// Append the same to Live Data Section
    $('#liveDeviceName').html(deviceListDropDown);

    $('#device-list').change(function () {

        var deviceId = $(this).val();
        console.log("device id: " + deviceId);
        if (deviceId == -1) {
            $('#info').hide();
            $('#row-sensors').hide();
            //$('#row-chartType').hide();
            $('#row-StartEnd').hide();
            return false;
        }


        var sensorlist = loadSensorList(deviceId);
        var sensors = $.parseJSON(sensorlist);
        var sensorsListDropDown;

        sensorsListDropDown = "<option value='-1'>-Any-</option>";
        $.each(sensors, function (i, sensorlist) {
            sensorsListDropDown += "<option type='" + sensorlist.Sensorid.Type + "' value='" + sensorlist.Sensorid.Id + "'>" + sensorlist.Sensorid.Name + "</option>";
        });

        $('#sensor-list').html(sensorsListDropDown);

        $('#row-sensors').fadeIn(1000);

    });


    $('#sensor-list').change(function () {

        var sensorId = $(this).val();

        if (sensorId == -1) {
            //$('#row-chartType').hide();
            $('#row-loadChart').hide();
            $('#row-StartEnd').hide();
            return false;
        }

        $('#row-StartEnd').fadeIn(1000);
        $('#row-loadChart').fadeIn(1000);
        //$('#row-chartType').fadeIn(1000);

    });

    /*$('#chartType-list').change(function () {

        var chartType = $(this).val();

        if (chartType == -1) {
            $('#row-loadChart').hide();
            return false;
        }

        $('#row-loadChart').fadeIn(1000);
    });*/


    /// Load Historic Chart
    $('#btnLoadChart').click(function (e) {
        e.preventDefault();

        //Update historic panel size
        $('#historic-panel').height(700);

        var datapages = loadData($('#sensor-list').val(), $('#startDate').val(), $('#endDate').val());
        if (datapages == "405") {
            // Start Time or end time later than current time
            $('#info').show();
            $('#info').html('Start Time or end time later than current time');
            $('#historic-data').hide();
        } else if (datapages == "406") {
            $('#info').show();
            $('#info').html('No Data gathered between these dates');
            $('#historic-data').hide();
        } else {
            $('#info').hide();
            initializeChart(datapages);
            $('#historic-data').fadeIn(1000);
        }
    });


    function loadData(sensorID, startDate, endDate) {

        //var startDate = $('#startDate').val();
        // var endDate = $('#endDate').val();
        var pageSize = 100;
      
        var pages = $.ajax({
            type: 'GET',
            url: "http://uclwebservicetest.cloudapp.net/Services/Chart.svc/sensordata/paeginfo?userid=" + getUserID() + "&sensorid=" + sensorID + "&start=" + startDate + "&end=" + endDate + "&pagesize=" + pageSize,
            contentType: "application/json; charset=utf-8",
            global: false,
            async: false,
            success: function (data) {
                console.log(data);

                return data;
            }
        }).responseText;

        var objPages = jQuery.parseJSON(pages);

        if (objPages.ErrorDetail == "Start Time or end time later than current time") {
            console.log("enter here");
            return "405";
        } else if (objPages.PageData == "") {
            console.log("enter here2");
            return "406";
        }
 
        return objPages;
    }
    /**
 * A small plugin for getting the CSV of a categorized chart
 */
    (function (Highcharts) {

        // Options
        var itemDelimiter = ',',  // use ';' for direct import to Excel
            lineDelimiter = '\n';

        var each = Highcharts.each;
        Highcharts.Chart.prototype.getCSV = function () {
            var xAxis = this.xAxis[0],
                formatEpoch,
                columns = [],
                line,
                csv = "",
                row,
                col;


            if (xAxis.categories) {
                columns.push(xAxis.categories);
                columns[0].unshift("");
            }

            //var i = 0;

            // var xAxisValues = this.series.xData;
            // console.log(xAxisValues);

            //for (var i = 0; i < xAxisValues.length; i++) {

            //    var epoch = xAxisValues[i];
            //    var humanreadable = new Date(epoch);
            //    console.log(humanreadable.toLocaleString());

            //}

            each(this.series, function (series) {
                //columns.push(series.xData);
                columns.push(series.yData);
                columns[columns.length - 1].unshift(series.name);
            });

            // Transform the columns to CSV
            for (row = 0; row < columns[0].length; row++) {
                line = [];
                for (col = 0; col < columns.length; col++) {
                    console.log(columns[col][row]);
                    line.push(columns[col][row]);
                }
                csv += line.join(itemDelimiter) + lineDelimiter;
            }
            return csv;
        };
    }(Highcharts));

    // Now we want to add "Download CSV" to the exporting menu. We post the CSV
    // to a simple PHP script that returns it with a content-type header as a 
    // downloadable file.
    // The source code for the PHP script can be viewed at 
    // https://raw.github.com/highslide-software/highcharts.com/master/studies/csv-export/csv.php

    Highcharts.getOptions().exporting.buttons.contextButton.menuItems.push({
        text: 'Download CSV',
        onclick: function () {
            Highcharts.post('http://www.highcharts.com/studies/csv-export/csv.php', {
                csv: this.getCSV()
            });
        }
    });
    function initializeChart(datapages) {
        var chart = new Highcharts.Chart({
            chart: {
                renderTo: 'historic-data',
                zoomType: 'x',
                spacingRight: 20
            },
            title: {
                text: 'Data gathered from sensor ' + '<b><i>' + $('#sensor-list option:selected').text() + '</b></i>' + ' of <b><i>' + $('#device-list option:selected').text() + '</b></i>device',
            },
            subtitle: {
                text: document.ontouchstart === undefined ?
                    'Click and drag in the plot area to zoom in' :
                    'Drag your finger over the plot to zoom in'
            },
            xAxis: {
                type: 'datetime',
                //  maxZoom: 14 * 24 * 3600000, // fourteen days
                title: {
                    text: null
                }
            },
            yAxis: {
                title: {
                    text: $('#sensor-list option:selected').attr('type')
                }
            },
            tooltip: {
                shared: true
            },
            legend: {
                enabled: false
            },
            plotOptions: {
                area: {
                    fillColor: {
                        linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
                        stops: [
                            [0, Highcharts.getOptions().colors[0]],
                            [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
                        ]
                    },
                    lineWidth: 1,
                    marker: {
                        enabled: false
                    },
                    shadow: false,
                    states: {
                        hover: {
                            lineWidth: 1
                        }
                    },
                    threshold: null
                }
            },
            series: [{
                type: 'area',
                name: $('#sensor-list option:selected').attr('type'),
                data: (function () {
                    var data = [];
                    var objData = [];

                    for (var i = datapages.PageData.length - 1; i >0 ; i--) {

                        var pageURI = datapages.PageData[i];
                        var dataResponse;

                        $.ajax({
                            type: 'GET',
                            url: pageURI,
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            global: false,
                            async: false,
                            success: function (response) {
                                dataResponse = JSON.parse(response);         
                            }
                        });
                        objData.push(dataResponse);
                    }
      
                    //console.log(objData);

                    $.each(objData, function (key, value) {                     
                        $.each(objData[key], function (idx, val) {

                            var datetime = new Date(val.time);
                            console.log(datetime.getTime());
                            data.push({
                                x: datetime.getTime(),
                                y: val.temperature
                            });
                        });                
                    });

                    return data;
                })()
            }]
        });
        $('#getcsv').click(function () {
            alert(chart.getCSV());
        });
    }

   

    /// Compare
    $('#compareDeviceNameScenario1').change(function () {
        var deviceId = $(this).val();
        if (deviceId == -1) {
            $('#compareInfo').hide();
            $('#compareRowSensorScenario1').hide();
            return false;
        }

        var sensorlist = loadSensorList(deviceId);
        var sensors = $.parseJSON(sensorlist);
        var sensorsListDropDown;

        sensorsListDropDown = "<option value='-1'>-Any-</option>";
        $.each(sensors, function (i, sensorlist) {
            sensorsListDropDown += "<option type='" + sensorlist.Sensorid.Type + "' value='" + sensorlist.Sensorid.Id + "'>" + sensorlist.Sensorid.Name + "</option>";
        });

        $('#compareRowSensorNameScenario1').html(sensorsListDropDown);
        $('#compareRowSensorScenario1').fadeIn(1000);
    });

    $('#compareDeviceNameScenario2').change(function () {
        var deviceId = $(this).val();
        if (deviceId == -1) {
            $('#compareInfo').hide();
            $('#compareRowSensorScenario2').hide();
            return false;
        }

        var sensorlist = loadSensorList(deviceId);
        var sensors = $.parseJSON(sensorlist);
        var sensorsListDropDown;

        sensorsListDropDown = "<option value='-1'>-Any-</option>";
        $.each(sensors, function (i, sensorlist) {
            sensorsListDropDown += "<option type='" + sensorlist.Sensorid.Type + "' value='" + sensorlist.Sensorid.Id + "'>" + sensorlist.Sensorid.Name + "</option>";
        });

        $('#compareRowSensorNameScenario2').html(sensorsListDropDown);

        $('#compareRowSensorScenario2').fadeIn(1000);
    });



    $('#compareRowSensorNameScenario1').change(function () {

        var sensorId = $(this).val();

        if (sensorId == -1) {
            $('#compareRowDeviceNameScenario2').hide();
            return false;
        }
        $('#compareRowDeviceNameScenario2').fadeIn(1000);
    });

    $('#compareRowSensorNameScenario2').change(function () {

        var sensorId = $(this).val();

        if (sensorId == -1) {
            $('#compareRowStartEnd').hide();
            //$('#compareRowChartLayout').hide();
            $('#compareRowLoadChart').hide();
            return false;
        }

        $('#compareRowStartEnd').fadeIn(1000);
        //$('#compareRowChartLayout').fadeIn(1000);
        $('#compareRowLoadChart').fadeIn(1000);

    });

    /// Load Compare Chart
    $('#compareBtnLoad').click(function (e) {
        e.preventDefault();

        var datapagesSensor1 = loadData($('#compareRowSensorNameScenario1').val(), $('#compareStart').val(), $('#compareEnd').val());
        var datapagesSensor2 = loadData($('#compareRowSensorNameScenario2').val(), $('#compareStart').val(), $('#compareEnd').val());

       
        $('#info').hide();
        initializeCompareChart(datapagesSensor1, datapagesSensor2);
        $('#compare-data').fadeIn(1000);

    });

    function initializeCompareChart(datapagesSensor1, datapagesSensor2) {
        $('#compare-data').highcharts({
            chart: {
                zoomType: 'x',
                spacingRight: 20
            },
            title: {
                text: 'Comparison Chart',
            },
            subtitle: {
                text: document.ontouchstart === undefined ?
                    'Click and drag in the plot area to zoom in' :
                    'Drag your finger over the plot to zoom in'
            },
            xAxis: {
                type: 'datetime',
                //  maxZoom: 14 * 24 * 3600000, // fourteen days
                title: {
                    text: null
                }
            },
            yAxis: {
                title: {
                    text: $('#compareRowSensorNameScenario1 option:selected').attr('type')
                }
            },
            tooltip: {
                shared: true
            },
            legend: {
                enabled: false
            },
            plotOptions: {
                area: {
                    fillColor: {
                        linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
                        stops: [
                            [0, Highcharts.getOptions().colors[0]],
                            [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
                        ]
                    },
                    lineWidth: 1,
                    marker: {
                        enabled: false
                    },
                    shadow: false,
                    states: {
                        hover: {
                            lineWidth: 1
                        }
                    },
                    threshold: null
                }
            },

            series: [{
                type: 'area',
                name: 'Sensor 1',
                data: (function () {
                    var data = [];

                    if (datapagesSensor1 == 406)
                        return data;
                    else {
                        var objData = [];

                        for (var i = datapagesSensor1.PageData.length - 1; i > 0 ; i--) {

                            var pageURI = datapagesSensor1.PageData[i];
                            var dataResponse;

                            $.ajax({
                                type: 'GET',
                                url: pageURI,
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                global: false,
                                async: false,
                                success: function (response) {
                                    dataResponse = JSON.parse(response);
                                }
                            });
                            objData.push(dataResponse);
                        }

                        //console.log(objData);

                        $.each(objData, function (key, value) {
                            $.each(objData[key], function (idx, val) {

                                var datetime = new Date(val.time);
                                console.log(datetime.getTime());
                                data.push({
                                    x: datetime.getTime(),
                                    y: val.temperature
                                });
                            });
                        });
                    }
                    return data;
                })()
            },{
                type: 'area',
                name: 'Sensor 2',
                data: (function () {
                    var data = [];

                    if (datapagesSensor2 == 406)
                        return data;
                    else {
                        var objData = [];

                        for (var i = datapagesSensor2.PageData.length - 1; i > 0 ; i--) {

                            var pageURI = datapagesSensor2.PageData[i];
                            var dataResponse;

                            $.ajax({
                                type: 'GET',
                                url: pageURI,
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                global: false,
                                async: false,
                                success: function (response) {
                                    dataResponse = JSON.parse(response);
                                }
                            });
                            objData.push(dataResponse);
                        }

                        //console.log(objData);

                        $.each(objData, function (key, value) {
                            $.each(objData[key], function (idx, val) {

                                var datetime = new Date(val.time);
                                console.log(datetime.getTime());
                                data.push({
                                    x: datetime.getTime(),
                                    y: val.temperature
                                });
                            });
                        });
                    }
                    return data;
                })()
            }]
        });
    }

    /// Live Data Section

    $('#liveDeviceName').change(function () {

        var deviceId = $(this).val();
        if (deviceId == -1) {
            $('#liveRowSensorName').hide();
            return false;
        }

        var sensorlist = loadSensorList(deviceId);
        var sensors = $.parseJSON(sensorlist);
        var sensorsListDropDown;

        sensorsListDropDown = "<option value='-1'>-Any-</option>";
        $.each(sensors, function (i, sensorlist) {
            sensorsListDropDown += "<option type='" + sensorlist.Sensorid.Type + "' value='" + sensorlist.Sensorid.Id + "'>" + sensorlist.Sensorid.Name + "</option>";
        });

        $('#liveSensorName').html(sensorsListDropDown);
        $('#liveRowSensorName').fadeIn(1000);
    });


    $('#liveSensorName').change(function () {

        var sensorId = $(this).val();

        if (sensorId == -1) {
            $('#liveRowLoadData').hide();
            return false;
        }

        $('#liveRowLoadData').fadeIn(1000);
    });
});